package com.jsh.frame.myframe2.manager;

import android.app.Application;
import android.content.Context;
import android.support.annotation.NonNull;

import com.google.gson.Gson;
import com.jsh.frame.myframe2.model.UserInfoModel;
import com.jsh.frame.myframe2.utils.PrefsUtil;


/**
 * 用户信息管理类
 * Created by Admin on 2016/7/28.
 */
public class UserManager {
    private static String KEY_USER_INFO = "key_user_info";

    private static UserManager userManager = new UserManager();
    private UserInfoModel userModel;
    private Context mContext;

    public static UserManager getInstance() {
        return userManager;
    }

    private UserManager() {
    }

    public void init(@NonNull Application application) {
        this.mContext = application.getApplicationContext();
        String json = PrefsUtil.read(mContext, KEY_USER_INFO, "");
        if (json != null && json.length() > 0) {
            this.userModel = fromJson(json);
        }
    }

    //检查是否初始化过
    private void checkInit() {
        if (this.mContext == null) {
            throw new ExceptionInInitializerError("UserManager is not initialized!");
        }
    }

    public UserInfoModel getUserModel() {
        checkInit();
        if (this.userModel == null) {
            return null;
        }
        return fromJson(toJson(this.userModel));
    }

    public void setUserModel(UserInfoModel userModel) {
        checkInit();
        this.userModel = userModel;
        PrefsUtil.write(mContext, KEY_USER_INFO, toJson(userModel));
    }

    /**
     * 判断用户是否登录
     *
     * @return true登录 false未登录
     */
    public boolean isLogin() {
        return userModel != null;
    }

    /**
     * 退出登陆
     */
    public void logout() {
        checkInit();
        this.userModel = null;
        PrefsUtil.write(mContext, KEY_USER_INFO, "");
    }

    private static String toJson(UserInfoModel tempUser) {
        return new Gson().toJson(tempUser);
    }

    private static UserInfoModel fromJson(String json) {
        return new Gson().fromJson(json, UserInfoModel.class);
    }
}
